﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Luna小店.UC.设计点;
using DevExpress.Utils.Win;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraLayout;
using DiaoPaiDaYin;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Demos.util;

namespace Luna小店.原型
{
    public partial class XtraForm2 : DevExpress.XtraEditors.XtraForm
    {
        public String OPTION_VALUE { get; set; }
        public String ITEM_NAME_CN { get; set; }
        //选择楼盘时，动态显示选中个数
        public LabelControl searchResult = new LabelControl() { Text = "已选择 0 个配料" };
        public XtraForm2()
        {
            InitializeComponent();
            #region sql
            String sql = "SELECT\n" +
"                a.DESIGN_ID id,\n" +
"                a.STYLE_CATEGORY_CD styleCategoryCD,\n" +
"                a.FILE_ID fileID,\n" +
"								d.ITEM_CD ITEM_CD,\n" +
"                a.ITEM_CD ITEM_VALUE,\n" +
"                a.ITEM_VALUE OPTION_VALUE,\n" +
"                a.ITEM_NAME_CN ITEM_NAME_CN,\n" +
"                file.UPLOAD_FILE \"picn\",\n" +
"                CONCAT( 'shirtmtm.com',file.FILE_PATH, file.UPLOAD_FILE ) \"picurl\",\n" +
"                a.ITEM_NAME_EN itemNameEN,\n" +
"                a.ITEM_NAME_JP itemNameJP,\n" +
"                IFNULL( a.ITEM_COST, 0 ) itemCost,\n" +
"                a.REMARKS remarks,\n" +
"                a.ENABLE_FLAG enableFlag,\n" +
"                a.DELETE_FLAG deleteFlag,\n" +
"                a.HAVETO_FLAG haveToFlag,\n" +
"                a.VERSION version,\n" +
"                a.CREATE_DATE createDate,\n" +
"                a.CREATE_USER \"createBy.id\",\n" +
"                a.UPDATE_USER \"updateBy.id\",\n" +
"                a.ITEM_SORT itemSort,\n" +
"                a.ITEM_CATEGORY_CD itemCategoryCD,\n" +
"                file.FILE_ID \"uploadFile.fileId\",\n" +
"                file.FILE_SOURCE \"uploadFile.fileSource\",\n" +
"                file.MODULE_KBN \"uploadFile.moduleKbn\",\n" +
"                file.FTP_FILE \"uploadFile.ftpFile\",\n" +
"                file.FILE_PATH \"uploadFile.filePath\",\n" +
"                CONCAT( p.FIRST_NAME, p.LAST_NAME ) \"updateBy.firstName\"\n" +
"                FROM\n" +
"                a_designoption_p a\n" +
"                LEFT JOIN a_login_user_p p ON a.UPDATE_USER = p.login_user_id\n" +
"                LEFT JOIN w_upload_file_p file ON a.FILE_ID = file.FILE_ID \n" +
"                LEFT JOIN a_ognization_desgin_r adr ON a.DESIGN_ID = adr.DESGIN_ID\n" +
"							  LEFT JOIN a_designoption_p d ON a.ITEM_CD=d.ITEM_VALUE	\n" +
"                WHERE\n" +
"                a.STYLE_CATEGORY_CD = 'STYLE_CATEGORY-SHIRT' and a.DESIGN_ID IN ( SELECT DESGIN_ID FROM a_shop_desgin_r WHERE SHOP_ID = 46 ) \n" +
"                AND a.ITEM_CD='4SCO'\n" +
"                AND a.DELETE_FLAG = 0 \n" +
"                AND adr.OGNIZATION_ID = 120 \n" +
"                -- AND (a.ITEM_VALUE LIKE '%+ str + \"%' OR a.ITEM_NAME_CN LIKE '%+ str + \"%') +\n" +
"                ORDER BY\n" +
"                a.item_sort,\n" +
"                a.UPDATE_DATE DESC;";
            String sql1 = "SELECT a_kuanshi_p.id,a_designoption_p.ITEM_CD,a_kuanshi_p.ITEM_CD AS `ITEM_VALUE`,a_kuanshi_p.ITEM_VALUE AS `OPTION_VALUE`,a_kuanshi_p.ITEM_NAME_CN FROM a_kuanshi_p LEFT JOIN a_designoption_p ON a_kuanshi_p.ITEM_CD=a_designoption_p.ITEM_VALUE WHERE PARENT_ID='-197710124171657216';";
            #endregion
            this.searchLookUpEdit设计点.Properties.DataSource = SQLmtm.GetDataTable(sql);
            //this.searchLookUpEdit设计点.Popup += new System.EventHandler(this.searchLookUpEdit设计点_Popup);
            //this.searchLookUpEdit1View.Click += new System.EventHandler(this.searchLookUpEdit设计点View_Click);
            //this.searchLookUpEdit设计点.CustomDisplayText += new DevExpress.XtraEditors.Controls.CustomDisplayTextEventHandler(this.searchLookUpEdit设计点_CustomDisplayText);
            //this.initNavigationPage(new UC设计点());
        }


        /// <summary>
        /// 初始化导航
        /// </summary>
        /// <param name="uC"></param>
        private void initNavigationPage(XtraUserControl uC)
        {
            uC.Dock = DockStyle.Fill;
            this.panel1.Controls.Clear();
            this.panel1.Controls.Add(uC);
        }

        #region 选择设计点
        /// <summary>
        /// 绑定清空事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit设计点_Popup(object sender, EventArgs e)
        {
            //得到当前SearchLookUpEdit弹出窗体
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clearBtn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
                SimpleButton btOK = new SimpleButton() { Name = "btOK", Text = "确定" };
                btOK.Click += btOK_Click;
                myLCI.Control = btOK;
                myLCI.SizeConstraintsType = SizeConstraintsType.Custom;//控件的大小设置为自定义
                myLCI.MaxSize = clearLCI.MaxSize;
                myLCI.MinSize = clearLCI.MinSize;
                myLCI.Move(clearLCI, DevExpress.XtraLayout.Utils.InsertType.Left);
                //添加一个label控件（选中结果显示）
                LayoutControlItem msgLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(a.Parent);
                msgLCI.TextVisible = false;
                msgLCI.Control = searchResult;
                msgLCI.Move(a, DevExpress.XtraLayout.Utils.InsertType.Left);
                msgLCI.BestFitWeight = 100;
            }
        }
        /// <summary>
        /// 点击选择后的行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit设计点View_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearBtn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit设计点.ToolTip = null;
            searchLookUpEdit设计点.EditValue = null;
            searchResult.Text = "已选择 0 个配料";
        }
        /// <summary>
        /// 选完之后的显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpEdit设计点_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            //if (null != e.Value)
            //    e.DisplayText = this.OPTION_VALUE+":"+this.ITEM_NAME_CN;
            if (FunctionHelper.GetValue(e.Value).Contains(","))
            {
                String str = "";
                var ss = GetLuValues()[1];
                foreach (String s in GetLuValues()[1])
                {
                    str = str + s + ",";
                }
                e.DisplayText = str;
            }
            else
            {
                var re = GetLuValues();
                if (re[0].Count == 1)
                {
                    e.DisplayText = re[1].First();
                }
                else
                {
                    e.DisplayText = "";
                }
            }
        }
        /// <summary>
        /// 楼盘确定按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btOK_Click(object sender, EventArgs e)
        {
            searchLookUpEdit设计点.ClosePopup();
        }
        #endregion

        private void searchLookUpEdit设计点_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //清除
            if (e.Button.Kind == ButtonPredefines.Clear)
            {
                luValues.Clear();
                searchLookUpEdit设计点.EditValue = null;
                searchResult.Text = "已选择 0 个配料";
            }
        }

        private void searchLookUpEdit设计点_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            var re = GetLuValues();
            searchLookUpEdit设计点.EditValue = string.Join(",", re[0].ToArray());
            searchLookUpEdit设计点.ToolTip = string.Join(",", re[1].ToArray());
        }
        public class LookUpMultSelectValues
        {
            public string FindText { get; set; }
            public List<string> SelectedValues { get; set; }
            public List<string> SelectedDisplays { get; set; }
        }
        private List<LookUpMultSelectValues> luValues = new List<LookUpMultSelectValues>();
        private List<string>[] GetLuValues()
        {
            List<string> r = new List<string>();
            foreach (var a in luValues)
            {
                r.AddRange(a.SelectedValues);
            }

            List<string> b = new List<string>();
            foreach (var a in luValues)
            {
                b.AddRange(a.SelectedDisplays);
            }
            return new[] { r.Distinct().ToList<string>(), b.Distinct().ToList<string>() };
        }

        private void searchLookUpEdit设计点_EditValueChanged(object sender, EventArgs e)
        {
            string estateId = FunctionHelper.GetValue(searchLookUpEdit设计点.EditValue);
            try
            {
                if (estateId != "")
                {
                    searchLookUpEdit设计点.Properties.Buttons[1].Visible = true;
                }
                else
                {
                    searchLookUpEdit设计点.ToolTip = null;
                    searchLookUpEdit设计点.Properties.View.ClearSelection();
                    searchLookUpEdit设计点.Properties.Buttons[1].Visible = false;
                }
            }
            catch
            {

            }
        }

        private void searchLookUpEdit1View_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            var a = searchLookUpEdit设计点.Properties.View.GetSelectedRows();
            var v = luValues.Find(b => b.FindText == searchLookUpEdit设计点.Properties.View.FindFilterText);
            if (v == null)
            {
                v = new LookUpMultSelectValues();
                v.FindText = searchLookUpEdit设计点.Properties.View.FindFilterText;
                v.SelectedValues = new List<string>();
                v.SelectedDisplays = new List<string>();
                luValues.Add(v);
            }
            if (a.Length > 0)
            {
                //新增状态时
                if (e.Action == CollectionChangeAction.Add)
                {
                    foreach (int rowHandle in a)
                    {
                        var vv = searchLookUpEdit设计点.Properties.View.GetRowCellValue(rowHandle, "OPTION_VALUE").ToString();//EstateID 是 Value Member
                        if (string.IsNullOrEmpty(v.SelectedValues.Find(b => b == vv)))
                        {
                            v.SelectedValues.Add(vv);
                            v.SelectedDisplays.Add(searchLookUpEdit设计点.Properties.View.GetRowCellValue(rowHandle, "ITEM_NAME_CN").ToString());//EstateName 是 Display Member
                        }

                    }
                }
            }
            //删除状态时
            if (e.Action == CollectionChangeAction.Remove)
            {
                List<string> dels = new List<string>();
                List<string> deld = new List<string>();

                for (int i = 0; i < v.SelectedValues.Count; i++)
                {
                    bool finded = false;
                    foreach (int rowHandle in a)
                    {
                        var vv = searchLookUpEdit设计点.Properties.View.GetRowCellValue(rowHandle, "OPTION_VALUE").ToString();//EstateID 是 Value Member
                        var vn = searchLookUpEdit设计点.Properties.View.GetRowCellValue(rowHandle, "ITEM_NAME_CN").ToString();//EstateName 是 Display Member
                        if (v.SelectedValues[i] == vv)
                        {
                            finded = true;
                            break;
                        }
                    }

                    if (!finded)
                    {
                        dels.Add(v.SelectedValues[i]);
                        deld.Add(v.SelectedDisplays[i]);
                    }
                }

                v.SelectedValues.RemoveAll(b => dels.Contains(b));
                v.SelectedDisplays.RemoveAll(b => deld.Contains(b));

                for (int i = 0; i < luValues.Count; i++)
                {
                    var ev = luValues[i];

                    ev.SelectedValues.RemoveAll(b => dels.Contains(b));
                    ev.SelectedDisplays.RemoveAll(b => deld.Contains(b));
                }
            }
            searchResult.Text = "已选择 " + GetLuValues()[0].Count + " 个楼盘";
        }

        private void XtraForm2_Load(object sender, EventArgs e)
        {
            
        }
    }
}